﻿// WAŻŻŻŻŻŻŻŻZNE!!!!!!!!!!!!!!!!!!!!!!!!!!!!1
// BUG - HINTBOXCLASS ZLE POKAZUJACY SIE JAK NAJEDZIESZ NA KLASE KTORA MA POKAZANY BACK CONTENT!!!
// ZOPTYMALIZOWAC

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Media.Effects;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections;
using RozpoznawanieCore;
using System.Threading;
using Microsoft.Windows.Controls.Ribbon;
using System.Windows.Media.Animation;
using System.Windows.Ink;
using System.IO;


namespace TouchUmlUI
{
    public enum UMLType { INTERFACE, CLASS, ACTOR, ACTION, NOTICE, ASSOCIATION, BYHAND };
    public enum DragType { MOVE, RESIZE_EAST, RESIZE_WEST, RESIZE_NORTH, RESIZE_SOUTH, RESIZE_SOUTH_EAST, RESIZE_SOUTH_WEST, RESIZE_NORTH_EAST, RESIZE_NORTH_WEST, NONE };

    public class Cmp : IComparer
    {
        public Cmp() : base() { }

        int IComparer.Compare(object x, object y)
        {

            if ((x == null) || (y == null))
            {
                return 0;
            }

            UMLObj obj1 = (UMLObj)x;
            UMLObj obj2 = (UMLObj)y;
            int z1 = Canvas.GetZIndex(obj1.guml.panel);
            int z2 = Canvas.GetZIndex(obj2.guml.panel);
            int m = -1;
            if (z1 > z2)
            {
                return 1 * m;
            }
            else
            {
                return -1 * m;
            }

        }
    }

    
    public interface ModelView
    {
        void odswiez();
    }    

    public partial class Window1 : Window
    {
        public String curDir; 
        public enum CopyType { COPY, CUT };
        public static bool freeDrawing = false;
        public static String APPTITLE = "TouchUML - Interactive UML Diagram Modelling";        
        public static bool modified = false;
        public static int resize_margin = 7;
        public static double scaleDelta = 0.1f;
        public static readonly DependencyProperty tabY;
        OurCanvas oc;
        private Diagram.ModelDiagramu model = new Diagram.ModelDiagramu("Nowy pakiet");
        BlurEffect myBlurEffect = new BlurEffect();
        int zindex = 1;
        Viewbox vb = new Viewbox();
        public UMLObj umlk;
        public UMLObj transformObj;
        public UMLObj activeUmlObj;
        public object activeObj;
        public ArrayList al = new ArrayList();
        public TreeModelView treeModelView;

        public static int object_counter = 1;
        private LocalizationManager localization = new LocalizationManager();

        //---------------------------------
        private UMLObj clipboardObj;
        public UCUTextRecognizer.HandWrite handWrite;
        private Image hint;
        public static CopyType copyType = CopyType.COPY;
        UMLObj mouseDownObj, mouseUpObj;
        UMLType wybor = 0;
        int lc = 0;        
        int dx, dy;
        int mx, my;
        int wx, wy;
        int ox, oy;
        DragType drag;
        DragType resizeType;        
        int drag_id;
        public OurCanvas active_canvas;
        public Boolean can_click = true;
        PopupMenuBase popup_menu;
        public HintBoxBase hintbox;
        double start_blur = 0.0f;
        List<UMLObj> toblur = new List<UMLObj>();
        private System.Windows.Forms.Timer Clock;
        Rozpoznawanie rozpoznawacz;
        Thread theThread;
        MRU mru;
        ScaleTransform scaleTransform = new ScaleTransform(1.0f, 1.0f);
        public ScrollViewer sv = new ScrollViewer();
        MessageHint messageHint;
        AppMenu appMenu;
        OurListBox olb = new OurListBox();
        public OurTabbedConrol tabbedControl = new OurTabbedConrol();
        public UMLObj orgObj = null;
        public Polozenie orgPolozenie;
        public String projectPath = LocalizationManager.DEFAULT_FILE_NAME;

        public void setBlurAll()
        {
            foreach (UMLObj u in toblur)
            {
                u.guml.panel.Effect = myBlurEffect;
            }
        }

        public void checkModified()
        {
            if (Window1.modified)
            {
                if (mywindow.Title[0].CompareTo('*') != 0)
                    mywindow.Title = "* " + mywindow.Title;
            }
            else
            {
                if (mywindow.Title[0].CompareTo('*') == 0)
                    mywindow.Title = mywindow.Title.Substring(2);
            }
        }

        public void insertToClipboard(UMLObj obj, bool setOrgObj)
        {
            Paste.IsEnabled = true;
            if (setOrgObj)
            {
                orgPolozenie = new Polozenie(obj.getX(), obj.getY(), obj.getWidth(), obj.getHeight());
                orgObj = obj;
            }
            if (clipboardObj != null)
                clipboardObj = null;
            clipboardObj = obj.Clone();
            clipboardObj.updateDependencyProperties();
        }

        public void pasteFromClipboard()
        {
            if (clipboardObj == null) return;
            Console.WriteLine("pasteFromClipboard()");
            active_canvas.al.Add(clipboardObj);
            //-----------------
            clipboardObj.setX(orgPolozenie.x);
            clipboardObj.setY(orgPolozenie.y);
            clipboardObj.setWidth(orgPolozenie.width);
            clipboardObj.setHeight(orgPolozenie.height);
            //-----------------
            clipboardObj.guml.canvas = active_canvas;
            active_canvas.Children.Add(clipboardObj.guml.panel);
            Diagram.ElementNaDiagramie end = clipboardObj.guml.obj_uml as Diagram.ElementNaDiagramie;
            end.polozenie.X = (int)clipboardObj.getX();
            end.polozenie.Y = (int)clipboardObj.getY();
            end.rozmiar.Width = (int)clipboardObj.getWidth();
            end.rozmiar.Height = (int)clipboardObj.getHeight();
            active_canvas.model.Elementy.Add(end);
            treeModelView.Refresh();
            //
            if (copyType == CopyType.COPY)
            {
                insertToClipboard(orgObj, false);
            }
            else
            {
                Paste.IsEnabled = false;
            }
        }

        public void UnblurAll()
        {
            foreach (UMLObj u in toblur)
            {
                u.guml.panel.Effect = null;
            }
        }

        public void Timer_Tick(object sender, EventArgs eArgs)
        {
            myBlurEffect.Radius += 0.04;
            if (myBlurEffect.Radius > 3) { Clock.Stop(); return; }
            setBlurAll();
        }

        public void refreshAllAssociations()
        {
            HashSet<AssociableObj> set = new HashSet<AssociableObj>();
            set.Clear();
            foreach (UMLObj uObj in active_canvas.al)
            {
                if (uObj is AssociationObj)
                {
                    AssociationObj aObj = uObj as AssociationObj;
                    set.Add(aObj.fromRef);
                    set.Add(aObj.toRef);
                }
            }
            foreach (AssociableObj aObj in set)
            {
                aObj.calculateNewPoints();

            }
        }

        public UMLObj findUmlObjByXY(double px, double py)
        {
            for (int i = active_canvas.al.Count - 1; i >= 0; i--)
            {
                Object obj = active_canvas.al[i];
                if (obj is UMLObj)
                {
                    UMLObj uobj = (UMLObj)obj;
                    double ox = InkCanvas.GetLeft(uobj.guml.panel);
                    double oy = InkCanvas.GetTop(uobj.guml.panel);
                    double owidth = uobj.guml.panel.ActualWidth;
                    double oheight = uobj.guml.panel.ActualHeight;
                    if ((px > ox) && (py > oy) && (px < ox + owidth) && (py < oy + oheight))
                    {
                        return uobj;
                    }
                }
            }
            return null;
        }

        public bool isAssociation(UMLObj fromObj, UMLObj toObj, StrokeCollection s)
        {

            if ((fromObj == null) || (toObj == null))
            {
                StylusPoint sp1 = s[0].StylusPoints[0];
                StylusPoint sp2 = s[0].StylusPoints[s[0].StylusPoints.Count - 1];

                fromObj = findUmlObjByXY(sp1.X, sp1.Y);
                toObj = findUmlObjByXY(sp2.X, sp2.Y);
            }

            System.Console.WriteLine("fromObj: " + fromObj + " toObj: " + toObj);


            if (fromObj == null) return false;
            if (toObj == null) return false;
            if (fromObj.Equals(toObj)) return false;

            if ((fromObj is AssociableObj) && (toObj is AssociableObj))
            {
                AssociableObj fromClass = (AssociableObj)fromObj;
                AssociableObj toClass = (AssociableObj)toObj;

                fromClass.calculateNewPoints();
                toClass.calculateNewPoints();
                SignalR.utworzAsocjacje(UMLType.ASSOCIATION, fromClass, toClass, active_canvas, s);

                return true;
            }

            return false;
        }

        private void zajmijSieWynikiem(WynikRozpoznawania wynik)
        {
            Console.WriteLine("Zajmuje sie wynikiem");
            active_canvas.Dispatcher.BeginInvoke(
            System.Windows.Threading.DispatcherPriority.Normal,
            new Action(
              delegate()
              {
                  if (wynik.nazwa != null)
                  {
                      if (isAssociation(null, null, active_canvas.Strokes)) { return; }

                      Console.WriteLine("Wynik: " + wynik.nazwa);
                      if (wynik.nazwa.CompareTo("class") == 0)
                      {
                          SignalR.utworzObiekt(UMLType.CLASS, new Polozenie(wynik.x1, wynik.y1, wynik.x2 - wynik.x1, wynik.y2 - wynik.y1), active_canvas, active_canvas.Strokes, true);
                      }
                      else if (wynik.nazwa.CompareTo("notatka") == 0)
                      {
                          SignalR.utworzObiekt(UMLType.NOTICE, new Polozenie(wynik.x1, wynik.y1, wynik.x2 - wynik.x1, wynik.y2 - wynik.y1), active_canvas, active_canvas.Strokes, true);
                      }
                      else if (wynik.nazwa.CompareTo("elipsa") == 0)
                      {
                          SignalR.utworzObiekt(UMLType.ACTION, new Polozenie(wynik.x1, wynik.y1, wynik.x2 - wynik.x1, wynik.y2 - wynik.y1), active_canvas, active_canvas.Strokes, true);
                      }
                      else if (wynik.nazwa.CompareTo("kolo") == 0)
                      {
                          SignalR.utworzObiekt(UMLType.INTERFACE, new Polozenie(wynik.x1, wynik.y1, wynik.x2 - wynik.x1, wynik.y2 - wynik.y1), active_canvas, active_canvas.Strokes, true);
                      }
                      else if (wynik.nazwa.CompareTo("aktor") == 0)
                      {
                          SignalR.utworzObiekt(UMLType.ACTOR, new Polozenie(wynik.x1, wynik.y1, wynik.x2 - wynik.x1, wynik.y2 - wynik.y1), active_canvas, active_canvas.Strokes, true);
                      }
                      else if (wynik.nazwa.CompareTo("x") == 0)
                      {
                          UMLObj f = findUmlObjByXY(wynik.x1, wynik.y1);
                          if (f != null) // jezeli to nie zaden obiekt
                          {
                              active_canvas.usunObiektUML(f);
                          }
                          else // to moze asocjacja 
                          {
                              AssociationObj ret = null;
                              for (int i = 0; i < active_canvas.al.Count; i++)
                              {
                                  UMLObj ui = active_canvas.al[i] as UMLObj;
                                  if (ui is AssociationObj)
                                  {
                                      AssociationObj ai = ui as AssociationObj;
                                      if ((wynik.x1 - 20 < ai.polyline[1].X1) && (wynik.x1 + 20 > ai.polyline[1].X1) && (wynik.y1 - 20 < ai.polyline[1].Y1) && (wynik.y1 + 20 > ai.polyline[1].Y1))
                                      {
                                          ret = ai;
                                          active_canvas.usunObiektUML(ai);
                                          active_canvas.UpdateLayout();
                                          treeModelView.Refresh();
                                          break;
                                      }
                                      if ((wynik.x1 - 20 < ai.polyline[1].X2) && (wynik.x1 + 20 > ai.polyline[1].X2) && (wynik.y1 - 20 < ai.polyline[1].Y2) && (wynik.y1 + 20 > ai.polyline[1].Y2))
                                      {
                                          ret = ai;
                                          active_canvas.usunObiektUML(ai);
                                          active_canvas.UpdateLayout();
                                          treeModelView.Refresh();
                                          break;
                                      }
                                  }
                              }
                              if (ret != null)
                              {
                                  ret.fromRef.associationObj.Remove(ret);
                                  ret.toRef.associationObj.Remove(ret);
                                  ret.calculatePolyline();
                                  ret.calculatePolyline();
                                  ret.updateDependencyProperties();
                                  ret.updateDependencyProperties();
                                  Console.WriteLine("RET: " + ret);
                              }
                          }
                      }

                  }
                  

                      try
                      {                          
                          if (wynik.strokeCollection.Count == 1)
                          {
                              if (wynik.strokeCollection[0].StylusPoints.Count < 12)
                              {
                                  //OurCanvas.MouseDownEvent();
                              }
                          }
                      }
                      catch (Exception e)
                      {
                          MessageBox.Show(e.Message);
                      }

                      try { active_canvas.Strokes.Remove(wynik.strokeCollection); }
                      catch (Exception e) { }
                      try { active_canvas.Strokes.Remove(wynik.zleStroki); }
                      catch (Exception e) { }
                  
              }
          ));
        }

        public void rozpoznawaj()
        {
            while (true)
            {
                rozpoznawacz = new Rozpoznawanie();
                WynikRozpoznawania wynik = rozpoznawacz.rozpoznawaj();
                Console.WriteLine("dostalem " + wynik.nazwa);
                zajmijSieWynikiem(wynik);
            }
        }

        private void inkCanvas2_MouseDown(object sender, MouseButtonEventArgs e)
        {         
            if (freeDrawing) return;
            gestyTeraz = false;
            rozpoznawacz.RysujeTeraz = true;
        }
        private bool gestyTeraz = false;
        public void OnGesture(object sender, InkCanvasGestureEventArgs e)
        {
            Console.WriteLine("Gesty!!!!!!!!!!!!!!!!!");
            if (true) return;
            Stroke s = e.Strokes[e.Strokes.Count - 1];

            if (isAssociation(null, null, e.Strokes)) { /*active_canvas.Strokes.Clear();*/ gestyTeraz = true; e.Handled = true; return; }

            Console.WriteLine("OnGesture");
            Console.WriteLine(sender.ToString());

            double sWidth = Math.Abs(s.StylusPoints[0].X - s.StylusPoints[s.StylusPoints.Count - 1].X);

            if ((s.StylusPoints.Count < 35) && (sWidth < 40)) { /*active_canvas.Strokes.Clear();*/ return; }

            double sPocz = s.StylusPoints[0].X;
            double sKon = s.StylusPoints[s.StylusPoints.Count - 1].X;
            double sY = s.StylusPoints[s.StylusPoints.Count / 2].Y;
            double sX = s.StylusPoints[0].X + (sKon - sPocz) / 2;

            // TODO: zoptymalizować pętlę
            foreach (object elem in active_canvas.al)
            {
                if (elem is KlasaObj)
                {
                    Console.WriteLine("elem is KlasaObj");
                    KlasaObj kObj = (KlasaObj)elem;
                    object result = kObj.DeletePointOnObject(sX, sY);
                    if (result != null)
                    {
                        Console.WriteLine("result.ToString(): " + result.ToString());
                        e.Handled = true;
                    }
                    else
                        Console.WriteLine("result == NULL!");
                }
            }

        }

        private void rysowanie_Click(object seneder, RoutedEventArgs e)
        {
            freeDrawing = false;
            active_canvas.EditingMode = InkCanvasEditingMode.Ink;
            active_canvas.Cursor = Cursors.Pen;
            EditMode.IsChecked = false;
            DrawMode.IsChecked = true;
            FreeMode.IsChecked = false;
            // ---
            SelectMode.IsChecked = false;
            EraseByStrokeMode.IsChecked = false;
            EraseByPointMode.IsChecked = false;
        }

        private void edycja_Click(object sender, RoutedEventArgs e)
        {
            Console.WriteLine("Edycja Click!");
            active_canvas.EditingMode = InkCanvasEditingMode.None;
            EditMode.IsChecked = true;
            DrawMode.IsChecked = false;
            FreeMode.IsChecked = false;
            freeDrawing = false;
            // ---
            SelectMode.IsChecked = false;
            EraseByStrokeMode.IsChecked = false;
            EraseByPointMode.IsChecked = false;

        }

        private void tekst_Click(object sender, RoutedEventArgs e)
        {
            Console.WriteLine("Tekst Click!");
        }

        private void inkCanvas2_MouseUp(object sender, MouseButtonEventArgs e)
        {
            Console.WriteLine("mouseUP-------------------------------");


            if (e.LeftButton == MouseButtonState.Released)
            {
                Window1.modified = true;
                checkModified();
                Console.WriteLine(freeDrawing);
                if (freeDrawing) return;
                StrokeCollection ss = new StrokeCollection();
                if (active_canvas.Strokes.Count > 0)
                {
                    ss.Add(active_canvas.Strokes[active_canvas.Strokes.Count - 1]);
                    if (isAssociation(null, null, ss)) { /*active_canvas.Strokes.Clear();*/

                        if (active_canvas.EditingMode == InkCanvasEditingMode.Ink)
                        {
                             rozpoznawacz.RysujeTeraz = false;
                        }
                        gestyTeraz = true; e.Handled = true; return; }
                    Stroke s = ss[ss.Count - 1];

                    Console.WriteLine(sender.ToString());

                    double sWidth = Math.Abs(s.StylusPoints[0].X - s.StylusPoints[s.StylusPoints.Count - 1].X);

                    // if ((s.StylusPoints.Count < 35) && (sWidth < 40)) { /*active_canvas.Strokes.Clear();*/ return; }

                    double sPocz = s.StylusPoints[0].X;
                    double sKon = s.StylusPoints[s.StylusPoints.Count - 1].X;
                    double sY = s.StylusPoints[s.StylusPoints.Count / 2].Y;
                    double sX = s.StylusPoints[0].X + (sKon - sPocz) / 2;

                    // TODO: zoptymalizować pętlę
                    foreach (object elem in active_canvas.al)
                    {
                        if (elem is KlasaObj)
                        {
                            Console.WriteLine("elem is KlasaObj");
                            KlasaObj kObj = (KlasaObj)elem;
                            object result = kObj.DeletePointOnObject(sX, sY);
                            if (result != null)
                            {
                                Console.WriteLine("result.ToString(): " + result.ToString());
                                e.Handled = true;
                                active_canvas.Strokes.Remove(s);
                                if (active_canvas.EditingMode == InkCanvasEditingMode.Ink)
                                {
                                    rozpoznawacz.RysujeTeraz = false;
                                }
                                return;
                            }
                            else
                            {

                                Console.WriteLine("result == NULL!");
                            }
                        }
                    }
                }





                Console.WriteLine("doszedlem do normalngo");
                if (active_canvas.EditingMode == InkCanvasEditingMode.Ink)
                {

                    if (active_canvas.Strokes.Count - 1 >= 0 && gestyTeraz == false)
                        rozpoznawacz.dodajStrolka(active_canvas.Strokes[active_canvas.Strokes.Count - 1]);
                    rozpoznawacz.RysujeTeraz = false;
                }
            }
        }

        public OurCanvasModel createNewCanvasModel()
        {
            OurCanvasModel newCanvasModel = new OurCanvasModel();
            newCanvasModel.UseCustomCursor = true;
            return newCanvasModel;
        }

        private void invertWorkType()
        {
            if (DrawMode.IsChecked==true)
            {
                DrawMode.IsChecked = false;
                EditMode.IsChecked = true;
                FreeMode.IsChecked = false;
            }
            else if (EditMode.IsChecked==true)
            {
                DrawMode.IsChecked = true;
                EditMode.IsChecked = false;
                FreeMode.IsChecked = false;
            }
            else if (FreeMode.IsChecked == true)
            {
                DrawMode.IsChecked = true;
                EditMode.IsChecked = false;
                FreeMode.IsChecked = false;
            }


            if (DrawMode.IsChecked == true)
            {
                active_canvas.EditingMode = InkCanvasEditingMode.Ink;
                active_canvas.Cursor = Cursors.Pen;
                freeDrawing = false;
            }
            else if (EditMode.IsChecked == true)
            {
                active_canvas.EditingMode = InkCanvasEditingMode.None;
                active_canvas.Cursor = Cursors.Arrow;
                freeDrawing = false;
            }
            else if (FreeMode.IsChecked == true)
            {
                active_canvas.EditingMode = InkCanvasEditingMode.Ink;
                active_canvas.Cursor = Cursors.Arrow;
                freeDrawing = true;
            }
        }

        public void stylusButtonDown(object sender, StylusButtonEventArgs e)
        {            
            e.Handled = true;
            if (activeUmlObj != null) return;
            if (activeObj != null) return;

            if (handWrite != null) return;
            if (popup_menu != null) return;

            if (e.StylusButton.Name.CompareTo("Barrel Switch") == 0)
            {
                Point p = e.GetPosition(active_canvas);
                UMLObj au = findUmlObjByXY(p.X, p.Y);

                if (au == null)
                {
                    invertWorkType();
                }
                else
                {
                    if (DrawMode.IsChecked == true)
                    {
                        invertWorkType();                        
                    }
                }

            }
            e.Handled = true;
        }

        public OurCanvas createNewCanvas()
        {
            OurCanvas newCanvas = new OurCanvas(this);
            newCanvas.MouseDown += lbl_MouseDown;
            newCanvas.MouseUp += lbl_MouseUp;
            newCanvas.MouseMove += lbl_MouseMove;
            newCanvas.PreviewMouseDown += inkCanvas2_MouseDown;
            newCanvas.MouseUp += inkCanvas2_MouseUp;
            newCanvas.PreviewStylusButtonDown += stylusButtonDown;
            newCanvas.IsHitTestVisible = true;
            newCanvas.UseCustomCursor = true;
            newCanvas.Cursor = Cursors.Pen;
            newCanvas.setScrollViewer(sv);
            newCanvas.SelectionChanged += new EventHandler(newCanvas_SelectionChanged);

            Binding bind1 = new Binding("ActualWidthProperty");
            bind1.Source = sv;
            bind1.Path = new PropertyPath(ScrollViewer.ActualWidthProperty);
            newCanvas.SetBinding(InkCanvas.WidthProperty, bind1);

            Binding bind2 = new Binding("ActualHeightProperty");
            bind2.Source = sv;
            bind2.Path = new PropertyPath(ScrollViewer.ActualHeightProperty);
            newCanvas.SetBinding(InkCanvas.HeightProperty, bind2);

            LinearGradientBrush myLinearGradientBrush = new LinearGradientBrush();
            myLinearGradientBrush.StartPoint = new Point(0, 0);
            myLinearGradientBrush.EndPoint = new Point(0, 1);
            myLinearGradientBrush.GradientStops.Add(new GradientStop(Color.FromRgb(255, 255, 255), 1.0));
            myLinearGradientBrush.GradientStops.Add(new GradientStop(Color.FromRgb(191, 219, 255), 0.0));
            newCanvas.Background = myLinearGradientBrush;
            return newCanvas;
        }

        void newCanvas_SelectionChanged(object sender, EventArgs e)
        {            
            InkCanvas ik = (InkCanvas)sender;
            foreach (UIElement ui in ik.GetSelectedElements())
            {
                if (ui is Canvas) {
                    if (SignalR.findUmlObjByCanvas(ui as Canvas) != null)
                    {
                        active_canvas.Select(null, null);
                        MessageBox.Show(LocalizationManager.CANNOT_SELECT,LocalizationManager.POPUP_TITLE, MessageBoxButton.OK, MessageBoxImage.Exclamation);                        
                        return;
                    }
                }
            }
        }

        public Window1()
        {
            InitializeComponent();
            hint = new Image();
            hint.Width = 54;
            hint.Height = 254;
            hint.Stretch = Stretch.Fill;
            hint.Opacity = 0.7;

            mywindow.Background = Brushes.Black;
            PopupMenuBase.windowParent = mywindow;
            mywindow.MinWidth = 600;
            mywindow.MinHeight = 300;
            model.DodajPrymitywyC();
            mru = MRU.Load("mrulist.dat");
            if (mru == null)
                mru = new MRU(5);

            ThreadStart thSt = new ThreadStart(rozpoznawaj);
            theThread = new Thread(thSt);
            theThread.Start();

            myBlurEffect.Radius = 0;
            myBlurEffect.KernelType = KernelType.Gaussian;
            drag = DragType.NONE;

            oc = createNewCanvas();


            //vb.Child = oc;
            //vb.Width = Double.NaN;
            //vb.Height = Double.NaN;
            /*oc.Width = 1024;
            oc.Height = 768;*/
            sv.Content = oc;

            sv.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
            sv.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;

            //mdp.LastChildFill = true;

            //RowDefinition r1, r2;
            //r1 = new RowDefinition();
            //r1.Height = new GridLength(19);
            //r2 = new RowDefinition();
            //r2.Height = GridLength.Auto;
            //cnt.RowDefinitions.Add(r1);
            //cnt.RowDefinitions.Add(r2);


            //System.Windows.Controls.Grid.SetRow(mdp, 1);            
            //sv.HorizontalAlignment = HorizontalAlignment.Stretch;
            //mdp.HorizontalAlignment = HorizontalAlignment.Stretch;
            active_canvas = oc;




            //            Binding bind8 = new Binding("ActualHeightProperty");
            //bind8.Source = canvasPanel;
            //bind8.Path = new PropertyPath(Canvas.ActualHeightProperty);

            treeModelView = new TreeModelView(model, this, 200, 400);
            treeModelView.setTabbedControl(tabbedControl);
            //treeModelView.SetBinding(Canvas.HeightProperty, bind8);            



            /*Binding bind1 = new Binding("ActualHeightProperty");
            bind1.Source = myribbon;
            bind1.Path = new PropertyPath(Ribbon.ActualHeightProperty);
            treeModelView.SetBinding(Canvas.TopProperty, bind1);*/

            //mdp.Children.Add(sv);
            // cnt.Children.Add(mdp);



            //Clock = new System.Windows.Forms.Timer();

            drag_id = -1;
            this.SizeChanged += Window1_SizeChanged;
            this.Closed += Window1_Closed;



            ///*Binding bind5 = new Binding("ActualWidthProperty");
            //bind5.Source = tab;
            //bind5.Path = new PropertyPath(TabControl.ActualWidthProperty);
            //t0.SetBinding(TabItem.WidthProperty, bind5);       */ 
            //Binding bind6 = new Binding("ActualWidthProperty");
            //bind6.Source = can;
            //bind6.Path = new PropertyPath(TabControl.ActualWidthProperty);
            //sv.SetBinding(ScrollViewer.WidthProperty, bind6); 
            //bind8 = new Binding("ActualHeightProperty");
            //bind8.Source = canvasPanel;
            //bind8.Path = new PropertyPath(Canvas.ActualHeightProperty);
            //sv.SetBinding(ScrollViewer.HeightProperty, bind8);

            //sv.HorizontalAlignment = HorizontalAlignment.Stretch;
            //sv.VerticalAlignment = VerticalAlignment.Stretch;
            sv.HorizontalScrollBarVisibility = ScrollBarVisibility.Visible;
            sv.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;

            //Binding bind2 = new Binding("ActualWidthProperty");
            //bind2.Source = canvasPanel;
            //bind2.Path = new PropertyPath(Canvas.ActualWidthProperty);
            //cnt.SetBinding(TabControl.WidthProperty, bind2);
            //Binding bind3 = new Binding("ActualHeightProperty");
            //bind3.Source = canvasPanel;
            //bind3.Path = new PropertyPath(Canvas.ActualHeightProperty);
            // cnt.SetBinding(TabControl.HeightProperty, bind3);

            // bind1 = new Binding("ActualWidthProperty");
            // bind1.Source = canvasPanel;
            // bind1.Path = new PropertyPath(Canvas.ActualWidthProperty);
            //// oc.SetBinding(InkCanvas.WidthProperty, bind1);
            Binding bind4 = new Binding("ActualWidthProperty");
            bind4.Source = mywindow;
            bind4.Path = new PropertyPath(Window.ActualWidthProperty);
            myribbon.SetBinding(Microsoft.Windows.Controls.Ribbon.Ribbon.WidthProperty, bind4);
            SignalR.windowParent = this;
            HintBoxBase.windowParent = this;
            OurTabbedConrol.windowParent = this;
            Paste.IsEnabled = false;
            this.Closing += new System.ComponentModel.CancelEventHandler(Window1_Closing);            
        }

        void Window1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (modified)
            {
                if (projectPath != null)
                {
                    MessageBoxResult result = MessageBox.Show(String.Format(LocalizationManager.ASK_SAVE, System.IO.Path.GetFileName(projectPath)), LocalizationManager.POPUP_TITLE, MessageBoxButton.YesNoCancel, MessageBoxImage.Question);
                    if (result == MessageBoxResult.Cancel) { e.Cancel = true; return; }
                    if (result == MessageBoxResult.Yes)
                    {
                        if (projectPath.CompareTo(LocalizationManager.DEFAULT_FILE_NAME) == 0)
                        {
                            saveAsFile_Click(sender,new RoutedEventArgs());
                        }
                        else
                        {
                            saveFile_Click(sender, new RoutedEventArgs());
                        }
                    }                    
                }
            }            
        }


        /* EditableTextBox */

        public void attributeName_dblClick(object sender, RoutedEventArgs e)
        {
            TextBox tb = (TextBox)sender;
            tb.IsReadOnly = false;
            tb.IsEnabled = true;
            tb.BorderThickness = new Thickness(1);
            tb.BorderBrush = Brushes.Gray;
            tb.SelectAll();
        }

        public void attributeName_Click(object sender, RoutedEventArgs e)
        {
            TextBox tb = (TextBox)sender;
            tb.Background = Brushes.GreenYellow;
            tb.Focus();
        }

        public void attributeName_LostFocus(object sender, RoutedEventArgs e)
        {
            TextBox tb = (TextBox)sender;
            GUML tbGuml = (GUML)tb.Tag;
            tbGuml.umlobj.Refresh();
            tb.IsReadOnly = true;
            tb.BorderThickness = new Thickness(0);
            tb.Background = Brushes.Transparent;
            try
            {
                tb.SelectionLength = 0;
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
            }
        }

        public void attributeName_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            attributeName_LostFocus(sender, null);
        }

        public void attributeName_TextChanged(object sender, EventArgs e)
        {
            TextBox tb = (TextBox)sender;
        }

        public void attributeName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Return)
            {
                attributeName_LostFocus(sender, null);
            }
        }

        public void sp_Loaded(object sender, RoutedEventArgs e)
        {
            StackPanel sp = (StackPanel)sender;
            GUIVisible item = (GUIVisible)sp.Tag;
            item.panel = sp;
            sp.Tag = item;
            /*if (sp.Tag is ItemAttribute)
            {
                ItemAttribute item = (ItemAttribute)sp.Tag;
                item.panel = sp;
                sp.Tag = item;
            }
            else if (sp.Tag is ItemMethod)
            {
                ItemMethod item = (ItemMethod)sp.Tag;
                item.panel;
            }*/
        }

        public void imgAttr_doubleClick(object sender, MouseEventArgs e)
        {

        }

        /* End EditableTextBox */


        private void Window1_Closed(object sender, EventArgs e)
        {
            theThread.Abort();
            mywindow.Dispatcher.InvokeShutdown();
        }

        public void Window1_SizeChanged(object sender, RoutedEventArgs e)
        {
            int ww = (int)(mywindow.ActualWidth);
            int hh = (int)(mywindow.ActualHeight);

            if (ww <= 300) return;
            if (hh <= 300) return;

            Console.WriteLine("SizeChanged: " + ww + " x " + hh);
            Canvas.SetLeft(hint, ww - 60);
            Canvas.SetTop(hint, myribbon.ActualHeight + 50);

            foreach (OurTab tab in tabbedControl.Tabs)
            {
                if (tab.canvas.ActualWidth < mywindow.ActualWidth)
                    tab.canvas.Width = Math.Abs(mywindow.ActualWidth);
                if (tab.canvas.ActualHeight < mywindow.ActualHeight)
                    tab.canvas.Height = Math.Abs(mywindow.ActualHeight);
            }

            if (!treeModelView.isDocked())
            {
                sv.Width = Math.Abs(ww - 15);
                sv.Height = Math.Abs(hh - myribbon.ActualHeight - 54);
                Canvas.SetTop(treeModelView, myribbon.ActualHeight + 19);
                treeModelView.setHeight(Math.Abs(hh - myribbon.ActualHeight - 54 - 1));
            }
            else
            {
                sv.Width = Math.Abs(ww - 15 - treeModelView.ActualWidth);
                sv.Height = Math.Abs(hh - myribbon.ActualHeight - 54);
                treeModelView.Visibility = Visibility.Visible;
                Canvas.SetLeft(treeModelView, ww - 15 - treeModelView.ActualWidth);
                Canvas.SetTop(treeModelView, myribbon.ActualHeight + 19);
                treeModelView.setHeight(Math.Abs(hh - myribbon.ActualHeight - 54 - 1));
            }
        }

        public void onChangeTab(object sender, RoutedEventArgs e)
        {
            if (sender is OurTabbedConrol)
            {
                OurTabbedConrol otc = sender as OurTabbedConrol;
                int id = otc.getSelectedId();
                if (id == 1)
                {
                    olb.model = model;
                    // olb.Refresh(otc);
                }
            }
        }

        private void chooseLang_Click(object sender, RoutedEventArgs e)
        {
            MenuItem item = sender as MenuItem;            
            for (int i = 0; i < ChooseLanguage.Items.Count; i++)
            {
                (ChooseLanguage.Items[i] as MenuItem).IsChecked = false;
            }
            item.IsChecked = true;
            localization.Load(item.Tag as string, mywindow);            
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            
            localization.Load("pl", this);

            for (int i = 0;i<localization.Languages.Count;i++) 
            {
                var lang = localization.Languages[i];
                MenuItem item = new MenuItem() { IsCheckable = true, Header = lang.getName(), Tag = lang.getLangName() };

                if (i == 0) 
                {
                    item.IsChecked = true;
                }

                item.Click += chooseLang_Click;

                ChooseLanguage.Items.Add(item);
            }
            

            curDir = Directory.GetCurrentDirectory();
            TextRecognizerSizer.Initalize();
            //            DockPanel.SetDock(tabbedControl, Dock.Top);
            canvasPanel.Children.Add(tabbedControl);
            Canvas.SetTop(sv, myribbon.ActualHeight + 19);
            Canvas.SetLeft(sv, 0);
            canvasPanel.Children.Add(sv);

            //MessageBox.Show(ribbonmenu.ActualWidth + " x " + ribbonmenu.ActualHeight);
            canvasPanel.MouseMove += windowMouseMove;


            /*
            oc1.Width = tab.ActualWidth;
            oc1.Height = tab.ActualHeight;*/

            DrawMode.IsChecked = true;



            RefreshMRU();

            Canvas.SetTop(tabbedControl, myribbon.ActualHeight);

            /*OurCanvasModel aModel = createNewCanvasModel();            
            olb.Width = 600;
            olb.Height = 500;
            olb.HorizontalAlignment = HorizontalAlignment.Stretch;
            olb.VerticalAlignment = VerticalAlignment.Stretch;
            aModel.Children.Add(olb);                        */

            tabbedControl.addTab(LocalizationManager.DEFAULT_DIAGRAM_NAME, false);
            //            tabbedControl.addTab("Model UML", false, aModel);
            tabbedControl.addOnChange(onChangeTab);
            tabbedControl.Select(0);
            tabbedControl.Refresh();
            tabbedControl.SetValue(Canvas.ZIndexProperty, 100);
            Grid.SetRow(tabbedControl, 0);

            Binding bind1 = new Binding("ActualHeightProperty");
            bind1.Source = myribbon;
            bind1.Path = new PropertyPath(Ribbon.ActualHeightProperty);
            tabbedControl.SetBinding(Canvas.TopProperty, bind1);
            canvasPanel.Children.Add(treeModelView);

            BitmapImage src = new BitmapImage();
            src.BeginInit();
            src.UriSource = new Uri("ikony\\modelicon.png", UriKind.Relative);
            src.EndInit();
            hint.Source = src;
            hint.Opacity = 0.8;
            hint.IsHitTestVisible = false;
            canvasPanel.Children.Add(hint);
            mywindow.WindowState = WindowState.Maximized;
        }

        private void RefreshMRU()
        {
            MRUList.Items.Clear();
            String[] list = mru.getList();
            for (int i = 0; i < list.Length; i++)
            {
                if (list[i] != null)
                {
                    RibbonHighlightingListItem rItem = new RibbonHighlightingListItem();
                    rItem.Content = (i + 1) + ". " + System.IO.Path.GetFileName(list[i]);
                    rItem.Tag = list[i];
                    rItem.MouseDown += new MouseButtonEventHandler(rItem_MouseDown);
                    MRUList.Items.Add(rItem);
                }
            }

        }

        void rItem_MouseDown(object sender, MouseButtonEventArgs e)
        {
            String path = (String)(((RibbonHighlightingListItem)sender).Tag);
            projectPath = path;
            ZapisOdczyt.WczytajListe(tabbedControl, projectPath);
            mru.addToList(projectPath);
            mru.Save("mrulist.dat");
            RefreshMRU();
            mywindow.Title = APPTITLE + " [ " + System.IO.Path.GetFileName(projectPath) + " ]";
            Window1.modified = false;
            checkModified();
        }

        /*private void gridClick(object sender, RoutedEventArgs e)
        {
            CheckBox cb = (CheckBox)sender;
            if (cb.IsChecked == true)
            {
                active_canvas.showGrid(Visibility.Visible);                
            }
            else
            {
                active_canvas.showGrid(Visibility.Hidden);                
            }
        }*/

        void tabSelChanged(object sender, SelectionChangedEventArgs args)
        {
            lc = 0;
        }

        HitTestFilterBehavior OnHitTestFilter(DependencyObject target)
        {
            System.Console.WriteLine(target.ToString());
            return HitTestFilterBehavior.Continue;
        }

        HitTestResultBehavior OnHitTestResult(HitTestResult result)
        {
            System.Console.WriteLine("HitResult=" + result.VisualHit.GetType().Name);
            return HitTestResultBehavior.Stop;
        }

        private void windowMouseMove(object sender, MouseEventArgs e)
        {
            int kx = (int)e.GetPosition(canvasPanel).X;
            int ky = (int)e.GetPosition(canvasPanel).Y;

            if ((kx > canvasPanel.ActualWidth - 2) && (ky > myribbon.ActualHeight + 60) && (ky < myribbon.ActualHeight + 280))
            {
                if (!treeModelView.isVisible())
                {
                    if (e.LeftButton != MouseButtonState.Pressed)
                    {
                        treeModelView.Show(true);
                    }
                }
            }

        }

        private void lbl_MouseMove(object sender, MouseEventArgs e)
        {
            if (handWrite != null) { active_canvas.Cursor = Cursors.Arrow; return; }

            if (active_canvas.Children.Contains(hintbox))
            {
                if (transformObj != null)
                {
                    hintbox.setPosition(transformObj.getX() + transformObj.guml.panel.ActualWidth, transformObj.getY() - 8);
                }
            }

            if (active_canvas.EditingMode != InkCanvasEditingMode.None) return;


            if (activeUmlObj == null)
            {
                if (activeObj == null)
                {
                    if (active_canvas.Children.Contains(hintbox))
                    {
                        if (!hintbox.isHiding())
                        {
                            hintbox.Hide(active_canvas);
                            hintbox = null;
                        }
                    }
                }
            }


            int kx = (int)e.GetPosition(active_canvas).X;
            int ky = (int)e.GetPosition(active_canvas).Y;

            Point pt = e.GetPosition((UIElement)sender);
            if (drag == DragType.NONE)
            {
                /* UMLObj result = null;
                 for (int i = 0; i < active_canvas.al.Count; i++)
                 {
                     UMLObj obj = (UMLObj)active_canvas.al[i];
                     int objw = (int)obj.guml.panel.ActualWidth;
                     int objh = (int)obj.guml.panel.ActualHeight;                    
                     if ((obj.getX() < pt.X) && (obj.getX() + objw > pt.X) && (pt.Y > obj.getY()) && (pt.Y < obj.getY() +objh)) {
                         result = obj;
                     }

                 }          */

                // UMLObj umlk = result;
                umlk = activeUmlObj;
                if (umlk != null)
                {

                    int poczx = (int)InkCanvas.GetLeft(umlk.guml.panel) + (int)umlk.guml.panel.ActualWidth - resize_margin;
                    int konx = poczx + resize_margin * 2;
                    int poczy = (int)InkCanvas.GetTop(umlk.guml.panel) + resize_margin;
                    int kony = poczy + (int)umlk.guml.panel.ActualHeight - resize_margin * 2;
                    // jezeli rozszerzam wszer (EAST)                    
                    if (((kx > poczx) && (kx < konx) && (ky > poczy) && (ky < kony)) && (!(umlk is AktorObj)))
                    {
                        active_canvas.Cursor = Cursors.SizeWE;
                        resizeType = DragType.RESIZE_EAST;
                        transformObj = umlk;
                        return;
                    }
                    // jezeli rozszerzam wszer (WEST)
                    poczx = (int)InkCanvas.GetLeft(umlk.guml.panel) - resize_margin;
                    konx = poczx + resize_margin * 2;
                    poczy = (int)InkCanvas.GetTop(umlk.guml.panel);
                    kony = poczy + (int)umlk.guml.panel.ActualHeight;
                    if (((kx > poczx) && (kx < konx) && (ky > poczy) && (ky < kony)) && (!(umlk is AktorObj)))
                    {
                        active_canvas.Cursor = Cursors.SizeWE;
                        resizeType = DragType.RESIZE_WEST;
                        transformObj = umlk;
                        return;
                    }
                    // jezeli rozszerzam w gore (NORTH)
                    /*poczx = (int)InkCanvas.GetLeft(umlk.guml.panel) + resize_margin;
                    konx = poczx + (int)umlk.guml.panel.ActualWidth - resize_margin * 2;
                    poczy = (int)InkCanvas.GetTop(umlk.guml.panel) - resize_margin;
                    kony = poczy + resize_margin * 2;
                    if ((kx > poczx) && (kx < konx) && (ky > poczy) && (ky < kony))
                    {
                        active_canvas.Cursor = Cursors.SizeNS;
                        resizeType = DragType.RESIZE_NORTH;
                      8  return;
                    }
                    */
                    //jezeli rozszerzam w dol (SOUTH)
                    poczx = (int)InkCanvas.GetLeft(umlk.guml.panel) + resize_margin;
                    konx = poczx + (int)umlk.guml.panel.ActualWidth - resize_margin * 2;
                    poczy = (int)InkCanvas.GetTop(umlk.guml.panel) + (int)umlk.guml.panel.ActualHeight - resize_margin;
                    kony = poczy + resize_margin * 2;
                    if (((kx > poczx) && (kx < konx) && (ky > poczy) && (ky < kony)) && (!(umlk is AktorObj)))
                    {
                        active_canvas.Cursor = Cursors.SizeNS;
                        resizeType = DragType.RESIZE_SOUTH;
                        transformObj = umlk;
                        return;
                    }
                    // jezeli rozszerzam w dol i w prawo
                    poczx = (int)InkCanvas.GetLeft(umlk.guml.panel) + (int)umlk.guml.panel.ActualWidth - resize_margin;
                    konx = poczx + resize_margin * 2;
                    poczy = (int)InkCanvas.GetTop(umlk.guml.panel) + (int)umlk.guml.panel.ActualHeight - resize_margin;
                    kony = poczy + resize_margin * 2;
                    if (((kx > poczx) && (kx < konx) && (ky > poczy) && (ky < kony)) && (!(umlk is AktorObj)))
                    {
                        active_canvas.Cursor = Cursors.SizeNWSE;
                        resizeType = DragType.RESIZE_SOUTH_EAST;
                        transformObj = umlk;
                        return;
                    }

                    // jezeli rozszerzam w dol i w lewo
                    /* poczx = (int)Canvas.GetLeft(umlk.guml.panel) - resize_margin;
                    konx = poczx + resize_margin * 2;
                    poczy = (int)Canvas.GetTop(umlk.guml.panel) + (int)umlk.guml.panel.ActualHeight - resize_margin;
                    kony = poczy + resize_margin * 2;
                    if ((kx > poczx) && (kx < konx) && (ky > poczy) && (ky < kony))
                    {
                        this.Cursor = Cursors.SizeNESW;
                        resizeType = DragType.RESIZE_SOUTH_WEST;
                        return;
                    } */

                    // jezeli rozszerzam w gore i w prawo                    
                    /*  poczx = (int)InkCanvas.GetLeft(umlk.guml.panel) + (int)umlk.guml.panel.ActualWidth - resize_margin;
                      konx = poczx + resize_margin * 2;
                      poczy = (int)InkCanvas.GetTop(umlk.guml.panel) + -resize_margin;
                      kony = poczy + resize_margin * 2;
                      if ((kx > poczx) && (kx < konx) && (ky > poczy) && (ky < kony))
                      {
                          active_canvas.Cursor = Cursors.SizeNESW;
                          resizeType = DragType.RESIZE_NORTH_EAST;
                          return;
                      }*/

                    // jezeli przesuwam
                    if (!umlk.showBackContent)
                    {
                        //Console.WriteLine("transformObj: " + umlk);
                        poczx = (int)InkCanvas.GetLeft(umlk.guml.panel);
                        konx = poczx + (int)umlk.guml.panel.ActualWidth - resize_margin;
                        poczy = (int)InkCanvas.GetTop(umlk.guml.panel);
                        kony = poczy + (int)umlk.guml.panel.ActualHeight;
                        if ((kx > poczx) && (kx < konx) && (ky > poczy) && (ky < kony))
                        {
                            transformObj = umlk;
                            active_canvas.Cursor = Cursors.SizeAll;
                            resizeType = DragType.MOVE;
                            return;
                        }
                    }
                    else
                    {
                        resizeType = DragType.NONE;
                        //transformObj = null;
                        if (active_canvas.EditingMode == InkCanvasEditingMode.None)
                            active_canvas.Cursor = Cursors.Arrow;
                        else
                            active_canvas.Cursor = Cursors.Pen;
                    }

                    // jezeli rozszerzam w gore i w lewo
                    /* poczx = (int)Canvas.GetLeft(umlk.guml.panel) - resize_margin;
                    konx = poczx + resize_margin * 2;
                    poczy = (int)Canvas.GetTop(umlk.guml.panel) + (int)umlk.guml.panel.ActualHeight - resize_margin;
                    kony = poczy + resize_margin * 2;
                    if ((kx > poczx) && (kx < konx) && (ky > poczy) && (ky < kony))
                    {
                        this.Cursor = Cursors.SizeNWSE;
                        resizeType = DragType.RESIZE_NORTH_WEST;
                        return;
                    } */

                    //resizeType = DragType.NONE;
                    //active_canvas.Cursor = Cursors.Arrow;
                }
                else
                {
                    //transformObj = null;
                    if (active_canvas.EditingMode == InkCanvasEditingMode.None)
                    {
                        resizeType = DragType.NONE;
                        active_canvas.Cursor = Cursors.Arrow;
                    }
                    else
                    {
                        active_canvas.Cursor = Cursors.Pen;
                    }
                }
            }


            if (drag == DragType.MOVE)
            {
                int tx = (int)e.GetPosition(active_canvas).X;
                int ty = (int)e.GetPosition(active_canvas).Y;
                dx = tx - ox;
                dy = ty - oy;
                int nx = mx + dx;
                int ny = my + dy;


                // UMLObj umlk = (UMLObj)active_canvas.al[drag_id];

                if (umlk == null) return;

                umlk.setX(nx);
                umlk.setY(ny);
                int right = nx + (int)umlk.guml.panel.ActualWidth;
                if (right > umlk.guml.canvas.Width)
                {
                    umlk.guml.canvas.Width = right;                    
                }
                int bottom = ny + (int)umlk.guml.panel.ActualHeight;
                if (bottom > umlk.guml.canvas.Height)
                {
                    umlk.guml.canvas.Height = bottom;
                }
                umlk.updateDependencyProperties();
            }
            else if (drag == DragType.RESIZE_EAST)
            {
                int tx = (int)e.GetPosition(active_canvas).X;
                int ty = (int)e.GetPosition(active_canvas).Y;
                dx = tx - ox;
                dy = ty - oy;
                int new_width = wx + dx;
                if (new_width <= 50) new_width = 50;
                int nx = (int)InkCanvas.GetLeft(umlk.guml.panel);
                umlk.guml.panel.Width = new_width;
                int right = nx + (int)umlk.guml.panel.ActualWidth;
                if (right > umlk.guml.canvas.Width)
                {
                    umlk.guml.canvas.Width = right + 50;
                }
                umlk.updateDependencyProperties();
            }
            else if (drag == DragType.RESIZE_WEST)
            {
                int tx = (int)e.GetPosition(active_canvas).X;
                int ty = (int)e.GetPosition(active_canvas).Y;
                dx = tx - ox;
                dy = ty - oy;
                InkCanvas.SetLeft(umlk.guml.panel, mx + dx);
                int new_width = wx - dx;
                if (new_width <= 50) new_width = 50;
                umlk.guml.panel.Width = new_width;
                umlk.updateDependencyProperties();
            }
            else if (drag == DragType.RESIZE_NORTH)
            {
                int tx = (int)e.GetPosition(active_canvas).X;
                int ty = (int)e.GetPosition(active_canvas).Y;
                dx = tx - ox;
                dy = ty - oy;
                InkCanvas.SetTop(umlk.guml.panel, my + dy);
                int new_height = wy - dy;
                if (new_height <= 50) new_height = 50;
                umlk.guml.panel.Height = new_height;
                umlk.updateDependencyProperties();
            }
            else if (drag == DragType.RESIZE_SOUTH)
            {
                int tx = (int)e.GetPosition(active_canvas).X;
                int ty = (int)e.GetPosition(active_canvas).Y;
                dx = tx - ox;
                dy = ty - oy;
                int new_height = wy + dy;
                if (new_height <= 50) new_height = 50;
                int ny = (int)InkCanvas.GetTop(umlk.guml.panel);
                umlk.guml.panel.Height = new_height;
                int bottom = ny + (int)umlk.guml.panel.ActualHeight;
                if (bottom > umlk.guml.canvas.Height)
                {
                    umlk.guml.canvas.Height = bottom;
                }
                umlk.updateDependencyProperties();
            }
            else if (drag == DragType.RESIZE_SOUTH_EAST)
            {
                int tx = (int)e.GetPosition(active_canvas).X;
                int ty = (int)e.GetPosition(active_canvas).Y;
                dx = tx - ox;
                dy = ty - oy;
                int new_width = wx + dx;
                int new_height = wy + dy;
                if (new_width <= 50) new_width = 50;
                if (new_height <= 50) new_height = 50;
                umlk.guml.panel.Width = new_width;
                umlk.guml.panel.Height = new_height;
                int nx = (int)InkCanvas.GetLeft(umlk.guml.panel);
                int ny = (int)InkCanvas.GetTop(umlk.guml.panel);
                int right = nx + (int)umlk.guml.panel.ActualWidth;
                if (right > umlk.guml.canvas.Width)
                {
                    umlk.guml.canvas.Width = right + 50;
                }
                int bottom = ny + (int)umlk.guml.panel.ActualHeight;
                if (bottom > umlk.guml.canvas.Height)
                {
                    umlk.guml.canvas.Height = bottom;
                }
                umlk.updateDependencyProperties();
            }
            else if (drag == DragType.RESIZE_NORTH_EAST)
            {
                int tx = (int)e.GetPosition(active_canvas).X;
                int ty = (int)e.GetPosition(active_canvas).Y;
                dx = tx - ox;
                dy = ty - oy;
                int new_width = wx + dx;
                int new_height = wy - dy;
                if (new_width <= 50) new_width = 50;
                if (new_height <= 50) new_height = 50;
                int nx = (int)InkCanvas.GetLeft(umlk.guml.panel);
                Canvas.SetTop(umlk.guml.panel, my + dy);
                umlk.guml.panel.Width = new_width;
                umlk.guml.panel.Height = new_height;
                int right = nx + (int)umlk.guml.panel.ActualWidth;
                if (right > umlk.guml.canvas.Width)
                {
                    umlk.guml.canvas.Width = right;
                }
                umlk.updateDependencyProperties();
            }
        }

        private void lbl_MouseUp(object sender, MouseEventArgs e)
        {
            mouseUpObj = activeUmlObj;            
            drag = DragType.NONE;
            drag_id = -1;
        }

        public bool checkRecognize()
        {
            if (handWrite != null)
            {
                bool rozp = false;
                try
                {
                    rozp = handWrite.Recognize();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                if (rozp)
                {
                    handWrite.Grid1.Children.Clear();
                    if (handWrite != null)
                    {
                        if (handWrite.Parent != null)
                        {
                            ((InkCanvas)handWrite.Parent).Children.Remove(handWrite);                            
                            SelectMode.IsEnabled = true;
                            EraseByPointMode.IsEnabled = true;
                            EraseByStrokeMode.IsEnabled = true;
                            FreeMode.IsEnabled = true;
                            DrawMode.IsEnabled = true;
                            EditMode.IsEnabled = true;
                            treeModelView.Refresh();
                            active_canvas.EditingMode = handWrite.editingMode;
                            handWrite = null;
                        }
                    }
                }                
                return true;

            }
            return false;
        }

        public void lbl_MouseDown(object sender, MouseEventArgs e)
        {

            if (checkRecognize())
            {
                e.Handled = true;
                return;
            }
            

            int kx = (int)e.GetPosition(active_canvas).X;
            int ky = (int)e.GetPosition(active_canvas).Y;



            mouseDownObj = activeUmlObj;

            if (!can_click)
            {
                if (true)
                {
                    myBlurEffect.Radius = 0;
                    UnblurAll();
                    toblur.Clear();
                    can_click = true;
                    if (active_canvas.Children.Contains(popup_menu))
                    {
                        popup_menu.gUmlObj.panel.Effect = null;
                        active_canvas.Children.Remove(popup_menu);
                        popup_menu = null;
                    }
                    if (appMenu != null)
                    {
                        if (active_canvas.Children.Contains(appMenu))
                        {
                            active_canvas.Children.Remove(appMenu);
                            appMenu = null;
                        }
                    }
                }
                return;
            }

            if (appMenu == null)
            {
                if (activeUmlObj == null)
                {
                    Console.WriteLine(e.MiddleButton == MouseButtonState.Pressed);
                    if (e.RightButton == MouseButtonState.Pressed)
                    {
                        //appMenu = new AppMenu(this, kx - 6, ky - 4);
                        //active_canvas.Children.Add(appMenu);
                        //can_click = false;
                    }
                }
            }





            if (e.RightButton == MouseButtonState.Pressed)
            {
                myBlurEffect.Radius = 0;
                setBlurAll();
                toblur.Clear();

                kx = (int)e.GetPosition(active_canvas).X;
                ky = (int)e.GetPosition(active_canvas).Y;
                /*                        Point pt = e.GetPosition((UIElement)sender);

                                            UMLObj result = null;
                                            for (int i = 0; i < active_canvas.al.Count; i++)
                                            {
                                                UMLObj obj = (UMLObj)active_canvas.al[i];
                                                int objw = (int)obj.guml.panel.ActualWidth;
                                                int objh = (int)obj.guml.panel.ActualHeight;   
                                                if ((obj.getX() < pt.X) && (obj.getX() + objw > pt.X) && (pt.Y > obj.getY()) && (pt.Y < obj.getY() + objh))
                                                {
                                                    result = obj;
                                                }

                                            }
                                */
                UMLObj umlk = activeUmlObj;

                if (umlk != null)
                {

                    can_click = false;

                    foreach (UMLObj ul in active_canvas.al)
                    {
                        if (ul.Equals((UMLObj)umlk) == false)
                        {
                            toblur.Add(ul);
                        }
                    }

                    start_blur = 0.0f;
                    myBlurEffect.Radius = start_blur;
                   /* Clock = new System.Windows.Forms.Timer();
                    Clock.Tick += Timer_Tick;
                    Clock.Interval = 1;
                    Clock.Start();*/

                    myBlurEffect.Radius = 2;
                    setBlurAll();

                    DropShadowEffect myDropShadowEffect = new DropShadowEffect();
                    Color myShadowColor = new Color();
                    myShadowColor.ScA = 1;
                    myShadowColor.ScB = 0;
                    myShadowColor.ScG = 0;
                    myShadowColor.ScR = 0;
                    myDropShadowEffect.Color = myShadowColor;
                    myDropShadowEffect.Direction = 320;
                    myDropShadowEffect.ShadowDepth = 0;
                    myDropShadowEffect.BlurRadius = 13;
                    myDropShadowEffect.Opacity = 0.3;
                    umlk.guml.panel.Effect = myDropShadowEffect;
                    

                    popup_menu = new PopupMenuClass(kx - 32, ky - 32);
                    popup_menu.gUmlObj = umlk.guml;
                    zindex++;
                    umlk.guml.canvas.Children.Remove(umlk.guml.panel);
                    umlk.guml.canvas.Children.Add(umlk.guml.panel);
                    active_canvas.Children.Add(popup_menu);
                }
            }



            if (e.LeftButton == MouseButtonState.Pressed)
            {
                if (wybor != UMLType.BYHAND)
                {
                    if (lc == 0) // tylko jezeli nie zaczalem rysowac to testuj czy przeciagac
                    {

                        kx = (int)e.GetPosition(active_canvas).X;
                        ky = (int)e.GetPosition(active_canvas).Y;
                        /*Point pt = e.GetPosition((UIElement)sender);

                            UMLObj result = null;
                            for (int i = 0; i < active_canvas.al.Count; i++)
                            {
                                UMLObj obj = (UMLObj)active_canvas.al[i];
                                int objw = (int)obj.guml.panel.ActualWidth;
                                int objh = (int)obj.guml.panel.ActualHeight;   
                                if ((obj.getX() < pt.X) && (obj.getX() + objw > pt.X) && (pt.Y > obj.getY()) && (pt.Y < obj.getY() + objh))
                                {
                                    result = obj;
                                }

                            }*/

                        UMLObj umlk = activeUmlObj;
                        transformObj = umlk;
                        if (umlk != null)
                        {
                            Console.WriteLine("BringToFront()");
                            active_canvas.Children.Remove(umlk.guml.panel);
                            active_canvas.Children.Add(umlk.guml.panel);
                            drag_id = active_canvas.al.IndexOf(umlk);
                            ox = kx;
                            oy = ky;
                            mx = (int)InkCanvas.GetLeft(umlk.guml.panel);
                            my = (int)InkCanvas.GetTop(umlk.guml.panel);
                            wx = (int)umlk.guml.panel.ActualWidth;
                            wy = (int)umlk.guml.panel.ActualHeight;
                            if (resizeType == DragType.NONE)
                                drag = DragType.MOVE;
                            else
                                drag = resizeType;
                            return;

                            can_click = false;

                        }
                    }


                }
            }
        }

        private void exit_Click(object sender, RoutedEventArgs e)
        {
            mywindow.Close();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            wybor = UMLType.CLASS;
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            wybor = UMLType.NOTICE;
        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {
        }



        private void About_Click(object sender, RoutedEventArgs e)
        {
            Canvas c = new Canvas();
            c.Width = mywindow.ActualWidth;
            c.Height = mywindow.ActualHeight;
            Canvas cBg = new Canvas();
            cBg.Opacity = 0.6f;
            cBg.Background = Brushes.Black;
            cBg.Width = mywindow.ActualWidth;
            cBg.Height = mywindow.ActualHeight;

            cBg.MouseDown += c_MouseDown;
            c.MouseDown += c_MouseDown;

            c.Children.Add(cBg);
            BitmapImage logo = new BitmapImage();
            logo.BeginInit();
            logo.UriSource = new Uri(new Uri(Directory.GetCurrentDirectory()), "ikony\\logo.png");
            logo.EndInit();
            Image logoImage = new Image();
            logoImage.Source = logo;
            logoImage.Width = 697;
            logoImage.Height = 482;
            Canvas.SetLeft(logoImage, 220);
            Canvas.SetTop(logoImage, 130);
            c.Children.Add(logoImage);

            Binding bind1 = new Binding("ActualWidthProperty");
            bind1.Source = mywindow;
            bind1.Path = new PropertyPath(Window.ActualWidthProperty);
            cBg.SetBinding(Canvas.WidthProperty, bind1);
            Binding bind2 = new Binding("ActualHeightProperty");
            bind2.Source = mywindow;
            bind2.Path = new PropertyPath(Window.ActualHeightProperty);
            cBg.SetBinding(Canvas.HeightProperty, bind2);

            DoubleAnimation anim = new DoubleAnimation(0, 1, new TimeSpan(0, 0, 0, 0, 600), FillBehavior.Stop);
            anim.AccelerationRatio = 0.7;
            c.BeginAnimation(Canvas.OpacityProperty, anim);
            Canvas.SetZIndex(c, 10000);
            canvasPanel.Children.Add(c);
        }

        void c_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Canvas c = sender as Canvas;
            if (c.Opacity == 1.0f)
            {
                DoubleAnimation dAnim = new DoubleAnimation(1, 0, new TimeSpan(0, 0, 0, 0, 600), FillBehavior.Stop);
                dAnim.AccelerationRatio = 0.6;
                dAnim.Completed += delegate(object o, EventArgs e2)
                {
                    mywindow.canvasPanel.Children.Remove(c);
                    c = null;
                };
                c.BeginAnimation(Canvas.OpacityProperty, dAnim);
            }
        }




        public void showMessageHint(String text)
        {
            showMessageHint(text, active_canvas);
        }

        public void showMessageHint(String text, OurCanvas oC)
        {
            foreach (UIElement elem in oC.Children)
            {
                if (elem is MessageHint)
                {
                    oC.Children.Remove(elem);
                    break;
                }
            }
            messageHint = new MessageHint(active_canvas, text, 10, 10, Brushes.Transparent, 5000, 2000);
            oC.Children.Add(messageHint);
        }

        private void OnIgnore(object sender, RoutedEventArgs e)
        {
        }

        private void paste_Click(object sender, RoutedEventArgs e)
        {
            pasteFromClipboard();
        }

        private void OnCanExecute(object target, CanExecuteRoutedEventArgs args)
        {
            args.CanExecute = true;
        }

        private void saveFile_Click(object sender, RoutedEventArgs e)
        {
            if (projectPath.CompareTo(LocalizationManager.DEFAULT_FILE_NAME) != 0)
            {
                try
                {
                    ZapisOdczyt.Zapisz(tabbedControl, projectPath);
                    Window1.modified = false;
                    checkModified();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(LocalizationManager.SAVE_EXCEPTION,LocalizationManager.POPUP_TITLE, MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            else
            {
                saveAsFile_Click(sender, e);
            }
        }

        private void openFile_Click(object sender, RoutedEventArgs e)
        {
            // try
            {
                System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog();
                dialog.Filter = LocalizationManager.TOUCH_UML_DIALOG_FILTER+" (*.tuml) |*.tuml| "+LocalizationManager.ALL_FILES_DIALOG_FILTER+" (*.*) | *.*";
                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    ZapisOdczyt.WczytajListe(tabbedControl, dialog.FileName);
                    mru.addToList(dialog.FileName);
                    mru.Save("mrulist.dat");
                    RefreshMRU();
                    projectPath = dialog.FileName;
                    mywindow.Title = APPTITLE + " [ " + System.IO.Path.GetFileName(projectPath) + " ]";
                    Window1.modified = false;
                    checkModified();
                }
            }
            //catch (Exception ex)
            //{
            //    MessageBox.Show("Wystąpił błąd podczas wczytywania pliku!", "Uwaga!", MessageBoxButton.OK, MessageBoxImage.Error);
            //}
        }


        public void usun_Click(object sender, RoutedEventArgs e)
        {
            if (hintbox == null) return;
            if (hintbox.umlObj == null) return;
            active_canvas.usunObiektUML(hintbox.umlObj);
            hintbox.Hide(active_canvas);
            hintbox = null;
        }

        public void obroc_Click(object sender, RoutedEventArgs e)
        {
            UMLObj kObj = null;

            if (hintbox == null) return;

            if (hintbox.umlObj is KlasaObj)
            {
                Console.WriteLine("hintbox.umlObj is KlasaObj");
                kObj = (KlasaObj)hintbox.umlObj;
            }
            else
            {
                Console.WriteLine("hintbox.umlObj is not a instance of KlasaObj");
            }

            if (kObj == null) return;

            bool changed = false;
            DoubleAnimation rotateAnimation = new DoubleAnimation();
            rotateAnimation.From = 0;
            rotateAnimation.To = 360;
            rotateAnimation.AccelerationRatio = 0.9;
            rotateAnimation.Duration = new Duration(new TimeSpan(0, 0, 0, 0, 800));
            rotateAnimation.RepeatBehavior = new RepeatBehavior(1);

            DoubleAnimation scaleAnimationX = new DoubleAnimation();
            scaleAnimationX.From = 1;
            scaleAnimationX.To = 0.1;
            scaleAnimationX.AutoReverse = true;
            scaleAnimationX.AccelerationRatio = 0.6;
            scaleAnimationX.DecelerationRatio = 0.4;
            scaleAnimationX.Duration = new Duration(new TimeSpan(0, 0, 0, 0, 400));
            scaleAnimationX.RepeatBehavior = new RepeatBehavior(1);

            DoubleAnimation scaleAnimationY = new DoubleAnimation();
            scaleAnimationY.From = 1;
            scaleAnimationY.To = scaleAnimationX.To;
            scaleAnimationY.AutoReverse = true;
            scaleAnimationY.AccelerationRatio = 0.6;
            scaleAnimationY.DecelerationRatio = 0.4;
            scaleAnimationY.Duration = new Duration(new TimeSpan(0, 0, 0, 0, 400));
            scaleAnimationY.RepeatBehavior = new RepeatBehavior(1);

            ScaleTransform sTransform = new ScaleTransform();
            sTransform.CenterX = kObj.guml.panel.ActualWidth / 2.0f;
            sTransform.CenterY = kObj.guml.panel.ActualHeight / 2.0f;
            RotateTransform rTransform = new RotateTransform();
            rTransform.CenterX = sTransform.CenterX;
            rTransform.CenterY = sTransform.CenterY;
            TransformGroup transformGroup = new TransformGroup();
            transformGroup.Children.Add(sTransform);
            transformGroup.Children.Add(rTransform);
            //rTransform.BeginAnimation(RotateTransform.AngleProperty, rotateAnimation);
            //sTransform.BeginAnimation(ScaleTransform.ScaleXProperty, scaleAnimation);
            //sTransform.BeginAnimation(ScaleTransform.ScaleYProperty, scaleAnimation);            
            NameScope.SetNameScope(this, new NameScope());
            kObj.guml.panel.RenderTransform = transformGroup;
            kObj.guml.panel.Name = "animationObject";
            this.RegisterName("animationObject", kObj.guml.panel);
            this.RegisterName("angleProperty", rTransform);
            this.RegisterName("scalePropertyX", sTransform);
            this.RegisterName("scalePropertyY", sTransform);
            Storyboard.SetTargetName(rotateAnimation, "angleProperty");
            Storyboard.SetTargetProperty(rotateAnimation, new PropertyPath(RotateTransform.AngleProperty));
            Storyboard.SetTargetName(scaleAnimationX, "scalePropertyX");
            Storyboard.SetTargetProperty(scaleAnimationX, new PropertyPath(ScaleTransform.ScaleXProperty));
            Storyboard.SetTargetName(scaleAnimationY, "scalePropertyY");
            Storyboard.SetTargetProperty(scaleAnimationY, new PropertyPath(ScaleTransform.ScaleYProperty));
            Storyboard storyboard = new Storyboard();
            storyboard.Children.Add(scaleAnimationX);
            storyboard.Children.Add(scaleAnimationY);
            storyboard.Children.Add(rotateAnimation);


            storyboard.CurrentTimeInvalidated += delegate(object o, EventArgs eArgs)
            {
                ClockGroup clockGroup = (ClockGroup)o;
                AnimationClock dAnim = (AnimationClock)clockGroup.Children[0];
                if (dAnim.CurrentProgress > 0.86)
                {
                    if (!changed)
                    {
                        changed = true;
                        kObj.generateBackContent();
                        kObj.swapToBackContent();
                    }
                }
            };

            storyboard.Begin(this);
            e.Handled = true;
        }

        private void newFile_Click(object sender, RoutedEventArgs e)
        {
            System.GC.Collect();
            if (!Window1.modified)
            {
                tabbedControl.Clear();
                tabbedControl.addTab(LocalizationManager.DEFAULT_DIAGRAM_NAME, true);
                treeModelView.setTabbedControl(tabbedControl);
                treeModelView.Refresh();
                treeModelView.UpdateLayout();
                tabbedControl.Select(0);
            }
            else
            {
                if (projectPath != null)
                {
                    MessageBoxResult result = MessageBox.Show(String.Format(LocalizationManager.ASK_SAVE, System.IO.Path.GetFileName(projectPath)), LocalizationManager.POPUP_TITLE, MessageBoxButton.YesNoCancel, MessageBoxImage.Question);
                        if (result == MessageBoxResult.Cancel) return;
                        if (result == MessageBoxResult.Yes)
                        {
                            if (projectPath.CompareTo(LocalizationManager.DEFAULT_FILE_NAME) == 0)
                            {
                                saveAsFile_Click(sender, e);
                            }
                            else
                            {
                                saveFile_Click(sender, e);
                            }
                        }
                        Window1.modified = false;
                        checkModified();
                        newFile_Click(sender, e);                    
                }
            }
        }

        private void saveAsFile_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.SaveFileDialog dialog = new System.Windows.Forms.SaveFileDialog();
            dialog.Filter = LocalizationManager.TOUCH_UML_DIALOG_FILTER+" (*.tuml) |*.tuml| "+LocalizationManager.ALL_FILES_DIALOG_FILTER+" (*.*) | *.*";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                ZapisOdczyt.Zapisz(tabbedControl, dialog.FileName);
                projectPath = dialog.FileName;
                mywindow.Title = APPTITLE + " [ " + System.IO.Path.GetFileName(projectPath) + " ]";
                Window1.modified = false;
                checkModified();
            }
        }

        public void zoomin_Click(object sender, RoutedEventArgs e)
        {
            scaleTransform.CenterX = active_canvas.ActualWidth / 2.0f + (double)sv.HorizontalOffset / (double)scaleTransform.ScaleX;
            scaleTransform.CenterY = active_canvas.ActualHeight / 2.0f + (double)sv.VerticalOffset / (double)scaleTransform.ScaleY;
            if (scaleTransform.ScaleX < 2.0)
            {
                scaleTransform.ScaleX += scaleDelta;
                scaleTransform.ScaleY += scaleDelta;                
                active_canvas.RenderTransform = scaleTransform;
            }
        }

        public void zoomout_Click(object sender, RoutedEventArgs e)
        {
            scaleTransform.CenterX = active_canvas.ActualWidth / 2.0f + (double)sv.HorizontalOffset / (double)scaleTransform.ScaleX;
            scaleTransform.CenterY = active_canvas.ActualHeight / 2.0f + (double)sv.VerticalOffset / (double)scaleTransform.ScaleY;
            if (scaleTransform.ScaleX > 1.1)
            {
                scaleTransform.ScaleX -= scaleDelta;
                scaleTransform.ScaleY -= scaleDelta;
                active_canvas.RenderTransform = scaleTransform;
            }
        }

        public void walidujModel_Click(object sender, MouseButtonEventArgs e)
        {
            showMessageHint("Walidacja modelu!");
        }

        private void checkWorkType(InkCanvas c)
        {
            if (c is OurCanvas)
            {
                OurCanvas cc = c as OurCanvas;
                EditMode.IsEnabled = true;
                DrawMode.IsEnabled = true;
                if (cc.ActiveEditingMode == InkCanvasEditingMode.None)
                {
                    EditMode.IsChecked = true;
                    DrawMode.IsChecked = false;
                }
                else
                {
                    EditMode.IsChecked = false;
                    DrawMode.IsChecked = true;
                }
            }
            else if (c is OurCanvasModel)
            {
                OurCanvasModel cc = new OurCanvasModel();
                EditMode.IsEnabled = false;
                DrawMode.IsEnabled = false;
            }
        }


        public void changeCanvas(InkCanvas newCanvas)
        {
            //newCanvas.Width = mywindow.ActualWidth;
            //newCanvas.Height = mywindow.ActualHeight;

            if (newCanvas is OurCanvas)
            {
                tabbedControl.showTabBackgroundShadow(true);
                active_canvas = newCanvas as OurCanvas;
                sv.Content = active_canvas;
                checkWorkType(active_canvas);
            }
            else if (newCanvas is OurCanvasModel)
            {
                tabbedControl.showTabBackgroundShadow(false);
                vb.Child = newCanvas;
                checkWorkType(newCanvas);
            }
        }

        public void exitApp_Click(object sender, MouseButtonEventArgs e)
        {
            exit_Click(sender, null);
        }

        public Polozenie getRandomPolozenie()
        {
            Random r = new Random();
            return new Polozenie(10 + r.Next() % 50 + sv.HorizontalOffset, 10 + r.Next() % 50 + sv.VerticalOffset, 200 + r.Next() % 100, 200 + r.Next() % 100);
        }

        // dodaj do modelu [ribbon - Wstaw]

        public void addClass_Click(object sender, RoutedEventArgs e)
        {
            SignalR.utworzObiekt(UMLType.CLASS, getRandomPolozenie(), active_canvas, null, true);
        }

        public void addInterface_Click(object sender, RoutedEventArgs e)
        {
            SignalR.utworzObiekt(UMLType.INTERFACE, getRandomPolozenie(), active_canvas, null, true);
        }

        public void addActor_Click(object sender, RoutedEventArgs e)
        {
            SignalR.utworzObiekt(UMLType.ACTOR, getRandomPolozenie(), active_canvas, null, true);
        }

        public void addAction_Click(object sender, RoutedEventArgs e)
        {
            SignalR.utworzObiekt(UMLType.ACTION, new Polozenie(10+sv.HorizontalOffset, 10+sv.VerticalOffset, 250, 90), active_canvas, null, true);
        }

        public void addNotice_Click(object sender, RoutedEventArgs e)
        {
            SignalR.utworzObiekt(UMLType.NOTICE, getRandomPolozenie(), active_canvas, null, true);
        }

        //

        public void zaznaczWModelu(Diagram.ElementNaDiagramie end)
        {
            if (treeModelView.isDocked() == false)
            {
                treeModelView.Show(true);                
            }
            treeModelView.ZaznaczWModelu(end, null);
        }

        public void free_Click(object sender, RoutedEventArgs e)
        {
            FreeMode.IsChecked = true;
            active_canvas.EditingMode = InkCanvasEditingMode.Ink;            
            freeDrawing = FreeMode.IsChecked.Value;
            active_canvas.Cursor = Cursors.Pen;
            if (freeDrawing)
            {
                DrawMode.IsChecked = false;
                EditMode.IsChecked = false;
            }
        }

        public void select_Click(object sender, RoutedEventArgs e)
        {
            EraseByPointMode.IsChecked = false;
            EraseByStrokeMode.IsChecked = false;
            if (SelectMode.IsChecked == false)
            {
                if (DrawMode.IsChecked == true)
                {
                    active_canvas.EditingMode = InkCanvasEditingMode.Ink;

                }
                else if (EditMode.IsChecked == true)
                {
                    active_canvas.EditingMode = InkCanvasEditingMode.None;
                }
                EditMode.IsEnabled = true;
                DrawMode.IsEnabled = true;
                FreeMode.IsEnabled = true;
            }
            else
            {
                EditMode.IsEnabled = false;
                DrawMode.IsEnabled = false;
                FreeMode.IsEnabled = false;
                active_canvas.EditingMode = InkCanvasEditingMode.Select;
            }
        }

        public void eraseByPoint_Click(object sender, RoutedEventArgs e)
        {
            EraseByStrokeMode.IsChecked = false;
            SelectMode.IsChecked = false;
            if (EraseByPointMode.IsChecked == false)
            {
                if (DrawMode.IsChecked == true)
                {
                    active_canvas.EditingMode = InkCanvasEditingMode.Ink;

                }
                else if (EditMode.IsChecked == true)
                {
                    active_canvas.EditingMode = InkCanvasEditingMode.None;
                }
                else if (FreeMode.IsChecked == true)
                {
                    freeDrawing = true;
                    active_canvas.EditingMode = InkCanvasEditingMode.Ink;
                }
                EditMode.IsEnabled = true;
                DrawMode.IsEnabled = true;
                FreeMode.IsEnabled = true;
            }
            else
            {
                EditMode.IsEnabled = false;
                DrawMode.IsEnabled = false;
                FreeMode.IsEnabled = false;
                active_canvas.EditingMode = InkCanvasEditingMode.EraseByPoint;
            }
        }

        public void eraseByStroke_Click(object sender, RoutedEventArgs e)
        {
            EraseByPointMode.IsChecked = false;
            SelectMode.IsChecked = false;
            if (EraseByStrokeMode.IsChecked == false)
            {
                if (DrawMode.IsChecked == true)
                {
                    active_canvas.EditingMode = InkCanvasEditingMode.Ink;

                }
                else if (EditMode.IsChecked == true)
                {
                    active_canvas.EditingMode = InkCanvasEditingMode.None;
                }
                else if (FreeMode.IsChecked == true)
                {
                    freeDrawing = true;
                    active_canvas.EditingMode = InkCanvasEditingMode.Ink;
                }
                EditMode.IsEnabled = true;
                DrawMode.IsEnabled = true;
                FreeMode.IsEnabled = true;
            }
            else
            {
                EditMode.IsEnabled = false;
                DrawMode.IsEnabled = false;
                FreeMode.IsEnabled = false;
                active_canvas.EditingMode = InkCanvasEditingMode.EraseByStroke;
            }
        }

        // --- ---- 

        private void saveToImage_Click(object sender, RoutedEventArgs e)
        {
            String file_name = "";            

            System.Windows.Forms.SaveFileDialog dialog = new System.Windows.Forms.SaveFileDialog();
                    dialog.Filter = LocalizationManager.BMP_DIALOG_FILTER+" (*.bmp)|*.bmp|"+LocalizationManager.PNG_DIALOG_FILTER+" (*.png)|*.png|"+LocalizationManager.JPG_DIALOG_FILTER+" (*.jpg)|*.jpg|"+LocalizationManager.TIFF_DIALOG_FILTER+" (*.tiff)|*.tiff";
            int fIndex = -1;

            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                file_name = dialog.FileName;
                fIndex = dialog.FilterIndex;
            }
            else
            {
                return;
            }

           // MessageBox.Show("fIndex: " + fIndex);
            //return;

            if (fIndex==1)
            {
                RenderTargetBitmap rtb = new RenderTargetBitmap((int)active_canvas.ActualWidth, (int)active_canvas.ActualHeight, 96d, 96d, PixelFormats.Default);
                rtb.Render(active_canvas);
                BmpBitmapEncoder encoder = new BmpBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(rtb));
                FileStream fs = File.Open(file_name, FileMode.Create);
                encoder.Save(fs);
                fs.Close();
            }
            else if (fIndex==3)
            {
                RenderTargetBitmap rtb = new RenderTargetBitmap((int)active_canvas.ActualWidth, (int)active_canvas.ActualHeight, 96d, 96d, PixelFormats.Default);
                rtb.Render(active_canvas);
                JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(rtb));
                FileStream fs = File.Open(file_name, FileMode.Create);
                encoder.Save(fs);
                fs.Close();
            }
            else if (fIndex==2)
            {
                RenderTargetBitmap rtb = new RenderTargetBitmap((int)active_canvas.ActualWidth, (int)active_canvas.ActualHeight, 96d, 96d, PixelFormats.Default);
                rtb.Render(active_canvas);
                PngBitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(rtb));
                FileStream fs = File.Open(file_name, FileMode.Create);
                encoder.Save(fs);
                fs.Close();
            }
            else if (fIndex==4)
            {
                RenderTargetBitmap rtb = new RenderTargetBitmap((int)active_canvas.ActualWidth, (int)active_canvas.ActualHeight, 96d, 96d, PixelFormats.Default);
                rtb.Render(active_canvas);
                TiffBitmapEncoder encoder = new TiffBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(rtb));
                FileStream fs = File.Open(file_name, FileMode.Create);
                encoder.Save(fs);
                fs.Close();
            }

            Directory.SetCurrentDirectory(curDir);
//            MessageBox.Show(String.Format(LocalizationManager.SUCC_EXPORT_IMAGE, dialog.FileName), LocalizationManager.POPUP_TITLE, MessageBoxButton.OK, MessageBoxImage.Information);
        }


        public List<AssociationObj> findAllAssociationsForObject(UMLObj aUmlObj)
        {
            List<AssociationObj> ret = new List<AssociationObj>();
            foreach (OurTab tab in tabbedControl.Tabs)
            {
                foreach (UMLObj um in ((OurCanvas)(tab.canvas)).al)
                {
                    if (um is AssociationObj)
                    {
                        AssociationObj am = um as AssociationObj;
                        if ((am.fromRef.Equals(aUmlObj)) || (am.toRef.Equals(aUmlObj)))
                        {
                            ret.Add(am);
                        }
                    }
                }
            }
            return ret;
        }
       
        public void fillTabs()
        {
            OpenDiagram.Items.Clear();
            foreach (OurTab tab in tabbedControl.Tabs)
            {
                MenuItem item = new MenuItem();
                DockPanel sp = new DockPanel();
                //sp.Orientation = Orientation.Horizontal;

                if (tab.getTabState() != TabState.HIDDEN)
                {
                    sp.Children.Add(new TextBlock(new Run(tab.getTitle())));
                    item.Header = sp;
                    item.Click += openTab_Click;
                }
                else
                {
                    TextBlock tb = new TextBlock();
                    tb.FontWeight = FontWeights.Bold;
                    tb.Text = tab.getTitle();
                    sp.Children.Add(tb);
                    item.Header = sp;
                    item.Click += showTab_Click;                    
                }
                if (tabbedControl.Tabs.Count > 1) // nie mozna usunac ostatniego diagramu
                {
                    HoverButton hv = new HoverButton("ikony\\deletetab.png", "ikony\\deletetabhover.png", 20, 23);
                    hv.Margin = new Thickness(7, -3, 0, 0);
                    hv.Tag = tab.getTabId();
                    hv.MouseDown += deleteTab_MouseDown;
                    hv.HorizontalAlignment = HorizontalAlignment.Right;
                    DockPanel.SetDock(hv, Dock.Right);
                    sp.Children.Add(hv);
                }
                OpenDiagram.Items.Add(item);
            }
        }

        public void deleteTab_MouseDown(object sender, MouseEventArgs e)
        {
            int tid = (int)(((HoverButton)sender).Tag);
            String tabTitle = tabbedControl.Tabs[tid].getTitle();
            MessageBoxResult res = MessageBox.Show(String.Format(LocalizationManager.CONFIRM_DELETE_DIAGRAM, tabTitle), LocalizationManager.POPUP_TITLE, MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (res == MessageBoxResult.Yes)
            {
                tabbedControl.deleteTab(tid);
            }
        }

        public void showTab_Click(object sender, RoutedEventArgs e)
        {
            MenuItem item = sender as MenuItem;
            TextBlock tb = item.Header as TextBlock;
            String str = tb.Text;
            int id = tabbedControl.findByTitle(str);

            if (id != -1)
            {
                if (tabbedControl.getSelectedId() != -1)
                {
                    tabbedControl.Tabs[tabbedControl.getSelectedId()].setTabState(TabState.NOT_SELECTED);
                }
                tabbedControl.Tabs[id].setTabState(TabState.SELECTED);
                tabbedControl.Refresh();
                tabbedControl.Select(id);
                tabbedControl.Refresh();
                changeCanvas(tabbedControl.Tabs[id].canvas);
            }
            fillTabs();
        }

        public void openTab_Click(object sender, RoutedEventArgs e)
        {            
            MenuItem item = sender as MenuItem;
            String str = item.Header as String;            
            int id = tabbedControl.findByTitle(str);
            
            if (id != -1)
            {
                tabbedControl.Select(id);
                tabbedControl.Refresh();
            }
            fillTabs();
        }

        public void showAllHints(bool a_show) 
        {
            foreach (OurTab tab in tabbedControl.Tabs) 
            {
                OurCanvas cnv = ((OurCanvas)tab.canvas);
                foreach (UMLObj u in cnv.al)
                {
                    u.showHints(a_show);
                }
            }
        }

        public void poleTekstowe_Click(object sender, RoutedEventArgs e)
        {
            if (Hint.Opacity == 0.5f)
            {
                Hint.Opacity = 1.0f;
                showAllHints(true);
            }
            else
            {                
                Hint.Opacity = 0.5f;
                showAllHints(false);
            }
        }

        public void saveToPHP_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.SaveFileDialog dialog = new System.Windows.Forms.SaveFileDialog();
            dialog.Filter = LocalizationManager.CSHARP_DIALOG_FILTER + " (*.php) |*.php| " + LocalizationManager.ALL_FILES_DIALOG_FILTER + " (*.*) | *.*";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                try
                {
                    FileStream fs2 = new FileStream(dialog.FileName, FileMode.Create);
                    Diagram.ModelDiagramu.model.GenerujKodPHP(fs2);
                    MessageBox.Show(LocalizationManager.SUCC_EXPORT_CSHARP, LocalizationManager.POPUP_TITLE, MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(String.Format(LocalizationManager.FAIL_EXPORT_CSHARP, ex.Message), LocalizationManager.POPUP_TITLE, MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
        public void saveToJava_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                try
                {
                    DirectoryInfo di = new DirectoryInfo(dialog.SelectedPath);
                    Diagram.ModelDiagramu.model.GenerujKodJava(di);
                    MessageBox.Show(LocalizationManager.SUCC_EXPORT_CSHARP, LocalizationManager.POPUP_TITLE, MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(String.Format(LocalizationManager.FAIL_EXPORT_CSHARP, ex.Message), LocalizationManager.POPUP_TITLE, MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
        public void saveToCSharp_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.SaveFileDialog dialog = new System.Windows.Forms.SaveFileDialog();
            dialog.Filter = LocalizationManager.CSHARP_DIALOG_FILTER+" (*.cs) |*.cs| "+LocalizationManager.ALL_FILES_DIALOG_FILTER+" (*.*) | *.*";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                try
                {
                    FileStream fs2 = new FileStream(dialog.FileName, FileMode.Create);
                    Diagram.ModelDiagramu.model.GenerujKodCSharp(fs2);
                    MessageBox.Show(LocalizationManager.SUCC_EXPORT_CSHARP, LocalizationManager.POPUP_TITLE, MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(String.Format(LocalizationManager.FAIL_EXPORT_CSHARP, ex.Message), LocalizationManager.POPUP_TITLE, MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

    }
        
 


}
